package com.bl.student.service.biz.percent.impl;

import com.bl.student.common.ApiResponseCode;
import com.bl.student.common.CommonServiceException;
import com.bl.student.dao.model.PercentEntity;
import com.bl.student.dao.repository.PayRepository;
import com.bl.student.dao.repository.PercentRepository;
import com.bl.student.service.biz.BaseService;
import com.bl.student.service.biz.percent.PercentService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
@Log4j2
public class PercentServiceImpl extends BaseService implements PercentService {

    @Autowired
    PercentRepository percentRepository;

    @Override
    public  void changePercent(String percent) {
        PercentEntity percentEntity = percentRepository.findOne("percent001");
        BigDecimal a = getBigDecimal(percent);
        if(a.compareTo(new BigDecimal("1.00")) <= 0 && a.compareTo(new BigDecimal("0.00")) >= 0) {
            percentEntity.setPercent(a);
            percentRepository.save(percentEntity);
        } else {
            throw new CommonServiceException(ApiResponseCode.DATA_EXISTED.getCode(), "比例范围超出规定值");
        }

    }

    @Override
    public BigDecimal getPercentInfo() {
        PercentEntity percentEntity = new PercentEntity();
        percentEntity = percentRepository.findOne("percent001");
        BigDecimal percent = percentEntity.getPercent();
        return percent;
    }

    /**
     * object -> BigDecimal 转换.
     * @param value
     * @return
     */
    public static BigDecimal getBigDecimal(Object value) {
        BigDecimal ret = null;
        if (value != null) {
            if (value instanceof BigDecimal) {
                ret = (BigDecimal) value;
            } else if (value instanceof String) {
                ret = new BigDecimal((String) value);
            } else {
                throw new ClassCastException("Not possible to coerce [" + value + "] from class "
                        + value.getClass() + " into a BigDecimal.");
            }
        }
        return ret;
    }


}
